import Vue from 'vue';
import Router from 'vue-router';
import initMenu from '@/utils/initMenu';
import routes from '@/routers';

let addState = false;
let _menus = JSON.parse(window.sessionStorage.getItem('_menus'));

const home = () => import('@pages/index/views/home.vue');
const notFound = () => import('@/components/404.vue');

const verify = ['home', 'store', 'questionsDetails', 'index', 'notFound']

Vue.use(Router)

const router = new Router({
  routes: [{
    path: '/',
    name: 'index',
    // component: home
    redirect: '/home/store'
  }, {
    path: '/404',
    name: 'notFound',
    component: notFound
  }]
})

router.beforeEach((to, from, next) => {
  if (!addState) {
    if (_menus) {
      initMenu(router, _menus)
    } else {
      initMenu(router, routes)
    }
    addState = true;
    next(to.path);
  } else {
    let token = window.sessionStorage.getItem('token');
    if (verify.indexOf(to.name) > -1 || !!token) {
      // console.log(to)
      next();
    } else if (!token) {
      window.location.replace('./signin.html');
    }
  }
})

export default router;
